import Helper from '@/common/helper'
import { isEmpty, isJsonObjectString, isObject, isString } from '@/common/helper/is'
import $platform from '@/common/platform'
import ROUTE from '@/router'
import $store from '@/store'
// #ifdef H5
import $wxsdk from '@/common/libs/sdk-h5-weixin'
// #endif
const homePath = TABBAR[0]
// 设置分享的平台渠道: 1=H5,2=微信公众号网页,3=微信小程序,4=App,...按需扩展
const platformMap = ['H5', 'WechatOfficialAccount', 'WechatMiniProgram', 'App']

// 设置分享方式: 1=直接转发,2=海报,3=复制链接,...按需扩展
const fromMap = ['forward', 'poster', 'link']

// 设置分享信息参数
const getShareInfo = (
  scene = {
    title: '', // 自定义分享标题
    desc: '', // 自定义描述
    image: '', // 自定义分享图片
    params: {}, // 自定义分享参数
    useScreenShots: false, // 使用当前页屏幕截取图 为true则image设置无效; 对小程序有效
  },
  poster = {
    // 自定义海报数据
    type: 'user',
  },
) => {
  let shareInfo = {
    title: '', // 分享标题
    desc: '', // 描述
    image: '', // 分享图片
    path: '', // 分享页面+参数
    link: '', // 分享Url+参数
    query: '', // 分享参数
    poster, // 海报所需数据
  }

  const shareConfig = $store.getters.platform.share

  // 自动拼接分享用户参数
  const query = buildSpmQuery(scene.params)
  shareInfo.query = query

  // 配置分享链接地址
  shareInfo.link = buildSpmLink(shareConfig.linkAddress, buildSpmPath(query))

  // 配置转发参数
  if (shareConfig.methods.includes('forward')) {
    if (shareConfig.forwardInfo.title === '' || shareConfig.forwardInfo.image === '') {
      // console.log('请在平台设置中配置转发信息')
    }
    // 设置自定义分享信息
    shareInfo.title = scene.title || shareConfig.forwardInfo.title
    shareInfo.image = scene.useScreenShots ? null : scene.image || shareConfig.forwardInfo.image
    shareInfo.desc = scene.desc || shareConfig.forwardInfo.desc
    shareInfo.path = buildSpmPath(query)
  }

  return shareInfo
}

// 构造spm分享参数
const buildSpmQuery = (params = {}) => {
  let userId = '0' // 设置分享者用户ID
  if (typeof params.userId === 'undefined') {
    if ($store.getters.isLogin) {
      userId = $store.getters.userInfo.user_id
    }
  }
  let page = homePath // 页面类型: 1=首页(默认),2=我的,3=活动（老带新）,...按需扩展
  if (typeof params.page !== 'undefined') {
    page = params.page
  }
  let query = '0' // 设置页面ID: 如商品ID、拼团ID、活动ID等
  if (typeof params.query !== 'undefined') {
    if (!isObject(params.query) && !isString(params.query)) throw new Error('query must be object or string')
    query = isObject(params.query) ? JSON.stringify(params.query) : encodeURIComponent(params.query)
  }
  let platform = platformMap.indexOf($platform.name) + 1
  let from = '1'
  if (typeof params.from !== 'undefined') {
    from = platformMap.indexOf(params.from) + 1
  }
  //spmParams = ...  可按需扩展
  return `spm=${userId}.${page}.${query}.${platform}.${from}`
}

// 构造页面分享参数
const buildSpmPath = (query) => {
  return `${homePath}?${query}`
}

// 构造分享链接
const buildSpmLink = (linkAddress = '', query) => {
  return `${linkAddress}${query}`
}

// 解析Spm
const decryptSpm = (spm) => {
  let shareParamsArray = spm.split('.')
  let shareParams = {
    spm,
    refererUId: 0,
    page: '',
    query: {},
    platform: '',
    from: '',
  }

  shareParams.refererUId = shareParamsArray[0]
  shareParams.page = shareParamsArray[1]
  shareParams.query = shareParamsArray[2]
  shareParams.platform = platformMap[shareParamsArray[3] - 1]
  shareParams.from = fromMap[shareParamsArray[4] - 1]

  const { refererUId, query, platform, from } = shareParams
  const queryObj = !isEmpty(query) && query != '0' ? (isJsonObjectString(query) ? JSON.parse(query) : Helper.getQueryParams(decodeURIComponent(query))) : {}
  const params = { refererUId, ...queryObj, platform, from }
  if (shareParams.page !== homePath) {
    setTimeout(() => {
      ROUTE.redirect(shareParams.page, params)
    })
  }
  return { ...shareParams, ...params }
}

// 更新公众号分享sdk
const updateShareInfo = (shareInfo) => {
  // #ifdef H5
  if ($platform.name === 'WechatOfficialAccount') {
    $wxsdk.updateShareInfo(shareInfo)
  }
  // #endif
}

const shareForwardWechat = ({ vm, scene = 'WXSceneSession', cb = undefined }) => {
  // #ifdef  H5
  if (['WechatOfficialAccount', 'H5'].includes($platform.name)) {
    $store.dispatch('modal/SetShareGuide', true)
    return
  }
  // #endif

  // #ifdef APP-PLUS
  const { MODE, VITE_WX_MP_GH_ID } = $store.getters.DefEnvCon
  uni.share({
    provider: 'weixin',
    scene: scene,
    type: 5, // 分享形式，如图文0、纯文字1、纯图片2、音乐3、视频4、小程序5等。不同分享服务商支持的形式不同
    title: vm.shareInfo.title,
    imageUrl: vm.shareInfo.image,
    miniProgram: {
      id: VITE_WX_MP_GH_ID,
      path: vm.shareInfo.path, // 要跳到的页面支持传参?a=1&b=2
      type: MODE === 'development' ? 1 : MODE === 'testing' ? 2 : 0, // 微信小程序版本类型 Number:  0-正式版； 1-测试版； 2-体验版。 默认值为0。
      webUrl: 'https://ctdcri.com/uni-universallinks/__UNI__FCB71E8/',
    },
    success: (res) => {
      console.log('success:' + JSON.stringify(res))
      typeof cb === 'function' && cb()
    },
    fail: (err) => {
      console.log('fail:' + JSON.stringify(err))
      typeof cb === 'function' && cb()
    },
  })
  // #endif
}
export default {
  getShareInfo,
  updateShareInfo,
  decryptSpm,
  shareForwardWechat,
}
